//
//  UserAccount.m
//  1-MushroomStreet-自定义tabbar
//
//  Created by xmg on 16/1/13.
//  Copyright © 2016年 grx. All rights reserved.
//

#import "UserAccount.h"
#import "NSString+KeepFile.h"

@interface UserAccount ()<NSCoding>

/**存储路径*/
@property (nonatomic,copy)NSString *filePath;


@end


@implementation UserAccount

/**
 *数据懒加载
 */
- (NSString *)filePath
{
    if (!_filePath) {
        NSString *plistName = @"userAccount.plist";
        _filePath = [[NSString alloc] init];
        _filePath = [plistName cachesDir];
    }
    return _filePath;
}


//通过获取的过期时间 的秒数,计算出真正的过期时间
- (NSDate *)expires_date{
    _expires_date = [[NSDate alloc] initWithTimeIntervalSinceNow:_expires_in];
    
    return _expires_date;
}

//提供字典转模型的方法
+ (instancetype)grx_userAccountWithDict:(NSDictionary *)dict{
    UserAccount *account = [[UserAccount alloc] init];
    
    //KVC赋值,但是属性需要与要转换的数据的key一一对应(可以通过重写下面的UndefinedKey方法避免)
    [account setValuesForKeysWithDictionary:dict];
    
    return account;
}


 // 利用KVC赋值时如果找不到对应的key就会调用,重写是为了避免因为不能一一对应而报出找不到key的错误
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{

}




//将当期对象写入文件中
- (BOOL)saveUserAccount{
    
    return  [NSKeyedArchiver archiveRootObject:self toFile:self.filePath];
}

//从文件中读取数据
- (instancetype)loadUserAccount{

    id objc = [NSKeyedUnarchiver unarchiveObjectWithFile:self.filePath];
    
    if (objc == nil) {
        return nil;
    }
    
    //判断AccessToken是否过期
    //当前时间和真正过期时间
    NSDate *date = self.expires_date;
    if ([[NSDate date] compare:date] == NSOrderedAscending) { //前面的比后面的日期小
//        NSLog(@"过期了");
        objc = nil;
        return objc;
    }
//    NSLog(@"没有过期");
   return  objc;

}


/*写入文件时调用*/
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    
    //把NSIntger类型转换成NSNumber,不然会报错
    /*
      error:Implicit conversion of 'NSInteger' (aka 'long') to 'id _Nullable' is disallowed with ARC
     */
    NSNumber *expires_in = [NSNumber numberWithInteger:self.expires_in];
    
    [aCoder encodeObject:_access_token forKey:@"access_token"];
    [aCoder encodeObject:expires_in forKey:@"expires_in"];
    [aCoder encodeObject:_uid forKey:@"uid"];
    [aCoder encodeObject:_expires_date forKey:@"expires_Date"];
}

/**
 读取文档的时候调用
 */
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    
    self = [super init];
    if(self != nil){
       
        _access_token = [aDecoder decodeObjectForKey:@"access_token"];
        self.expires_in = [[aDecoder decodeObjectForKey:@"expires_in"] integerValue];
        _uid = [aDecoder decodeObjectForKey:@"uid"];
        _expires_date = [aDecoder decodeObjectForKey:@"expires_Date"];
    }
    return self;
}


//判断用户是否已经登录
- (BOOL)isLogin{
    return [self loadUserAccount] != nil;
}


@end
